import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;

public class ChapterMerger {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: java ChapterMerger <directoryPath>");
            return;
        }

        String directoryPath = args[0];
        Path outputPath = Paths.get(directoryPath, "merged.txt");

        try {
            mergeChapterFiles(directoryPath, outputPath.toString());
            System.out.println("合并完成，输出文件: " + outputPath);
        } catch (IOException e) {
            System.err.println("处理文件时出错: " + e.getMessage());
        }
    }

    public static void mergeChapterFiles(String inputDir, String outputFile) throws IOException {
        // 正则匹配 数字_章节名.txt 格式
        Pattern pattern = Pattern.compile("^(\\d+)_(.+)\\.txt$");
        
        // 存储章节信息，使用TreeMap自动按数字排序
        Map<Integer, ChapterInfo> chapters = new TreeMap<>();
        Set<String> seenChapterNames = new HashSet<>();

        // 遍历目录中的文件
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(inputDir))) {
            for (Path file : stream) {
                if (!Files.isRegularFile(file)) continue;

                String filename = file.getFileName().toString();
                Matcher matcher = pattern.matcher(filename);
                
                if (matcher.matches()) {
                    int chapterNum = Integer.parseInt(matcher.group(1));
                    String chapterName = matcher.group(2).trim();
                    
                    // 跳过章节名重复的文件
                    if (seenChapterNames.contains(chapterName)) {
                        System.out.println("跳过重复章节: " + filename);
                        continue;
                    }
                    seenChapterNames.add(chapterName);
                    
                    // 读取文件内容
                    String content = new String(Files.readAllBytes(file)).trim();
                    chapters.put(chapterNum, new ChapterInfo(chapterName, content));
                }
            }
        }

        // 写入合并后的文件
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {
            for (Map.Entry<Integer, ChapterInfo> entry : chapters.entrySet()) {
                ChapterInfo chapter = entry.getValue();
                
                // 写入章节标题(独占一行)
                writer.write(chapter.name);
                writer.newLine();
                
                // 写入章节内容
                writer.write(chapter.content);
                writer.newLine();
                writer.newLine(); // 章节间空一行
            }
        }
    }

    static class ChapterInfo {
        String name;
        String content;

        ChapterInfo(String name, String content) {
            this.name = name;
            this.content = content;
        }
    }
}